﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Write.NET.Entities;

namespace Write.NET.Repositories
{
    /// <summary>
    /// Implementation of IRepository of User type
    /// </summary>
    public class UserRepository : IRepository<User>
    {
        private WriteNetEntityModelContainer _dbContext;

        public UserRepository(WriteNetEntityModelContainer dbContext)
        {
            _dbContext = dbContext;
        }

        /// <summary>
        /// Get all User objects
        /// </summary>
        /// <returns>All Users</returns>
        public IQueryable<User> GetAll()
        {
            return _dbContext.Users;
        }

        /// <summary>
        /// Get an User object with matching id
        /// </summary>
        /// <param name="id">User Id</param>
        /// <returns>An user object with matching user id</returns>
        public User GetById(int id)
        {
            return _dbContext.Users.SingleOrDefault(p => p.UserId == id);
        }

        /// <summary>
        /// Get an User object with matching name
        /// </summary>
        /// <param name="name">User Name</param>
        /// <returns>An user object with matching user name</returns>
        public User GetByName(string name)
        {
            return _dbContext.Users.SingleOrDefault(p => p.UserName.ToLower().Equals(name.ToLower()));
        }

        /// <summary>
        /// Add a new User object
        /// </summary>
        /// <param name="t">New User object to be added</param>
        public void Add(User t)
        {
            _dbContext.Users.Add(t);
            _dbContext.SaveChanges();
        }

        /// <summary>
        /// Update existing User object with a new User object
        /// </summary>
        /// <param name="t">User object, the old object will be udpated to</param>
        public void Update(User t)
        {
            var existingUser = _dbContext.Users.SingleOrDefault(p => p.UserId == t.UserId);
            existingUser = t;
            _dbContext.SaveChanges();
        }

        /// <summary>
        /// Delete an User object with matching id
        /// </summary>
        /// <param name="id">User id</param>
        public void Delete(int id)
        {
            var existingUser = _dbContext.Users.SingleOrDefault(p => p.UserId == id);
            _dbContext.Users.Remove(existingUser);
            _dbContext.SaveChanges();
        }
    }
}
